from odoo import fields, models, api
from odoo.exceptions import UserError
from ...api.encapsulate.carriers import Carriers
from ...api.encapsulate.shipment import Shipment

# odoo 继承，会根据继承顺序，为父子类关系
# class RPShipOrderInheritTest(models.Model):
#     _inherit = 'rp.ship.order'

#     @api.depends('step_one', 'step_two', 'step_three', 'step_four', 'step_five', 'step_six', 'pay_flag')
#     def _compute_state(self):
#         super()._compute_state()
#         print(11111)


class RPShipOrderInherit(models.Model):
    _inherit = "rp.ship.order"

    # 重新查询邮路功能，添加直接对接shippypro查询
    # def action_get_available_shipper_mail_route(self):
    #     result = super().action_get_available_shipper_mail_route()
    #     # 获取发件地址信息
    #     # sender = self.ship_from
    #     from_address = Shipment.address(
    #         self.send_first_name,
    #         self.send_company_name,
    #         self.send_country_id.code,
    #         self.send_state_id.name,
    #         self.send_city_id.name,
    #         self.send_street,
    #         self.send_postal_code_id.name,
    #         self.send_phone,
    #         "",
    #     )
    #     # 获取收件地址信息
    #     # receiver = self.ship_to
    #     to_address = Shipment.address(
    #         self.receive_first_name,
    #         self.receive_company_name,
    #         self.receive_country_id.code,
    #         self.receive_state_id.name,
    #         self.receive_city_id.name,
    #         self.receive_street,
    #         self.receive_postal_code_id.name,
    #         self.receive_phone,
    #         "",
    #     )
    #     # 获取包裹信息
    #     parcel_list = []
    #     parcel_desc = ""
    #     parcel_values = 0.0
    #     for p in self.rp_parcel_ids:
    #         parcel_list.append(
    #             {
    #                 "length": p.depth,
    #                 "width": p.width,
    #                 "height": p.height,
    #                 "weight": p.weight,
    #                 "parcel_id": "",
    #                 "parcel_type": "",
    #             }
    #         )
    #         parcel_desc += p.desc
    #         parcel_values += p.values
    #     parcels = Shipment.parcels(parcel_list, parcel_desc, parcel_values)
    #     rates = Shipment.getRates(from_address, to_address, parcels, {})
    #     dynamic_route = []
    #     for rate in rates["Rates"]:
    #         # 判断该邮路本地是否配置
    #         local_routes = self.env["rp.courier.mail.route"].search(
    #             [
    #                 ("third_server_id", "=", rate["carrier_id"]),
    #                 ("third_route_name", "=", rate["service"]),
    #                 ("third_type", "=", "shippypro"),
    #             ]
    #         )
    #         if len(local_routes) == 0:
    #             continue
    #         # 邮路本地配置后，跳过
    #         # todo 添加匹配本地邮路规则相关功能，暂时使用本地承运人邮路是否配置体积重量为标准，应该更加详细，例如是否配置具体的配送范围等等，或者添加标识flag作为判断
    #         if len(local_routes) > 0 and local_routes[0].volume_weight_id:
    #             continue
    #             # match = self.env["rp.available.shipper.mail.route.tran"].search([("id", "in", local_routes.ids)])
    #             # if len(match) > 0:
    #             #     continue
    #             # else:
    #         # 本地没有配置，判断是否存在托运商
    #         local_route = local_routes[0]
    #         local_shippers = self.env["rp.shipper"].search(
    #             [("courier_id", "=", local_route.courier_id.id)]
    #         )
    #         if len(local_shippers) == 0:
    #             local_shipper = self.env["rp.shipper"].create(
    #                 {
    #                     "courier_id": local_route.courier_id.id,
    #                     "name": local_route.courier_id.name,
    #                     "code": local_route.courier_id.code,
    #                     "operation_dropoff": False,
    #                     "operation_pickup": True,
    #                     "operation_collect": False,
    #                     "operation_delivery": True,
    #                 }
    #             )
    #         else:
    #             local_shipper = local_shippers[0]

    #         default_aging = self.env["rp.aging"].search([])[0]
    #         # 托运商邮路默认时效，用于自动生成的邮路
    #         aging = (
    #             local_route.aging_ids[0] if len(local_route.aging_ids) > 0 else False
    #         )
    #         if not aging:
    #             aging = default_aging
    #         # 判断是否存在托运商邮路
    #         local_shipper_routes = self.env["rp.shipper.mail.route"].search(
    #             [("courier_mail_route_id", "=", local_route.id)]
    #         )
    #         if len(local_shipper_routes) == 0:
    #             # todo 添加时效
    #             local_shipper_route = self.env["rp.shipper.mail.route"].create(
    #                 {
    #                     "courier_id": local_route.courier_id.id,
    #                     "shipper_id": local_shipper.id,
    #                     "name": local_route.third_route_name,
    #                     "courier_mail_route_id": local_route.id,
    #                     "operation_dropoff": False,
    #                     "operation_pickup": True,
    #                     "operation_collect": False,
    #                     "operation_delivery": True,
    #                 }
    #             )
    #         else:
    #             local_shipper_route = local_shipper_routes[0]

    #         base_price = rate["rate"]
    #         sale_adjusted_price = 0
            
    #         # todo 可以添加判断，价格小于多少不显示，价格等于0不显示等等
            
    #         # 费用明细
    #         # for p in rate["detailed_pricing"]:
    #         #     base_price += p["price"]
    #         # 匹配价格调整规则
    #         price_adjust_rule = local_route.price_adjust_rule
    #         if not price_adjust_rule:
    #             price_adjust_rule = local_route.courier_id.default_price_adjust_rule
    #         if price_adjust_rule:
    #             sale_adjusted_price = (
    #                 base_price + price_adjust_rule.value
    #                 if price_adjust_rule.type == "number"
    #                 else base_price * price_adjust_rule.value
    #             )

            
    #         dr = {
    #             "shipper_mail_route_id": local_shipper_route.id,
    #             "shipper_id": local_shipper.id,
    #             "actual_weight": 1,
    #             "rounded_weight": 1,
    #             "aging_id": aging.id,
    #             "tag_price": base_price,
    #             "sale_adjusted_price": (
    #                 sale_adjusted_price if sale_adjusted_price > 0 else base_price
    #             ),
    #         }
    #         dynamic_route.append(dr)
    #     if len(dynamic_route) > 0:
    #         available_smr = self.env["rp.available.shipper.mail.route.tran"].create(
    #             dynamic_route
    #         )
    #         temp_str = result["domain"].split("[")
    #         temp_str = temp_str[len(temp_str) - 1]
    #         temp_str = temp_str.split("]")[0]
    #         old_ids = temp_str.split(",")
    #         result["domain"] = (
    #             ("[('id','in',%s)]" % (str(available_smr.ids + old_ids)))
    #             .replace(", ''", "")
    #             .replace(",''", "")
    #         )
    #     return result

    @api.depends(
        "step_one",
        "step_two",
        "step_three",
        "step_four",
        "step_five",
        "step_six",
        "pay_flag",
    )
    def _compute_state(self):
        super()._compute_state()
        for s in self:
            if s.state in ["done", "invoiced"] and s.shipper_mail_route_id.courier_mail_route_id.is_third_server and s.shipper_mail_route_id.courier_mail_route_id.rp_third_route_id:
                rcd = self.shipment_ids[0]
                if not rcd.label_url:
                    rcd.create_shippypro_order()  # 调用创建ShipPyPro订单接口
                # s.update({'shipment_flag': True, 'shipment_id': rcd.id})

    @api.onchange("tail_postal_office_id", "hold_for_pickup_flag")
    def correos_adept(self):
        correos = self.env["rp.courier"].search([("name", "=", "Correos")])
        hold_for_pickup = self.hold_for_pickup_flag
        if self.courier_id == correos and hold_for_pickup:
            point = self.env["rp.courier.options"].search(
                [("name", "=", "correospoint")], limit=1
            )
            pointid = self.env["rp.courier.options"].search(
                [("name", "=", "correospointid")], limit=1
            )
            self.update({"rp_ship_order_added_service_line_ids": [(5, 0)]})
            self.update(
                {
                    "rp_ship_order_added_service_line_ids": [
                        (
                            0,
                            0,
                            {
                                "rp_ship_order_id": self.id,
                                "courier_options_id": point.id,
                                "options_type": point.type,
                                "flag": True,
                                "char_one": "1",
                            },
                        ),
                        (
                            0,
                            0,
                            {
                                "rp_ship_order_id": self.id,
                                "courier_options_id": pointid.id,
                                "options_type": pointid.type,
                                "flag": True,
                                "char_one": self.tail_postal_office_id.shippypro_id,
                            },
                        ),
                    ]
                }
            )
        else:
            self.update({"rp_ship_order_added_service_line_ids": [(5, 0)]})

    @api.onchange("get_tail_postal_office_flag")
    def fulfillment_of_tail(self):
        """尾程满足(获取尾程代理点信息)"""
        if self.step_three:
            correos = self.env["rp.courier"].search([("name", "=", "Correos")])
            hold_for_pickup = self.hold_for_pickup_flag
            if self.courier_id == correos and hold_for_pickup:
                carrier_name = self.courier_id.name
                carrier_id = self.shipper_service_id.courier_service_id.shippypro_id
                country_code = self.receive_country_id.code
                postal_code = self.receive_postal_code_id.name
                city_name = self.receive_city_id.name
                flag, result = Carriers.get_carrier_options(
                    carrier_name, carrier_id, country_code, postal_code, city_name
                )
                if flag:
                    if result["Options"]["correospoint"]["label"] == "Point":
                        postal_office_dict = result["Options"]["correospoint"][
                            "parameters"
                        ]["correospointid"]
                        postal_office_dict = {
                            value: key for key, value in postal_office_dict.items()
                        }  # 字典key value置换
                        postal_office_list = []
                        for k, v in postal_office_dict.items():
                            rcd = self.env["rp.courier.postal.office"].search(
                                [("shippypro_id", "=", k)]
                            )
                            if rcd:
                                postal_office_list.append(rcd.id)
                            else:
                                rcd = self.env["rp.courier.postal.office"].create(
                                    {
                                        "rp_courier_id": self.courier_id.id,
                                        "name": v,
                                        "country_id": self.receive_country_id.id,
                                        "zip": v[v.rfind("(") + 1 : v.rfind(")")].split(
                                            " "
                                        )[-1],
                                        "shippypro_id": k,
                                    }
                                )
                                postal_office_list.append(rcd.id)
                        return {
                            "domain": {
                                "tail_postal_office_id": [
                                    ("id", "in", postal_office_list)
                                ]
                            }
                        }
                    else:
                        raise UserError("label != Point,数据异常，联系开发")
                else:
                    raise UserError(result)
